package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 新增规则
     *
     * @param alertRuleDto
     */
    @Override
    public void alertRuleCreate(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insertAlertRule(alertRule);
    }

    /**
     * 分页查询规则
     *
     * @param pageNum
     * @param pageSize
     * @param alertRuleName
     * @param functionName
     * @param productKey
     * @return
     */
    @Override
    public PageResponse<AlertRuleVo> getPageAlertRule(Integer pageNum, Integer pageSize, String alertRuleName, String functionName, String productKey) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.selectPageAlertRule(alertRuleName, functionName, productKey);
        page.getResult().forEach(alertRuleVo -> {
            String rules = CharSequenceUtil
                    .format("{}{}{},持续{}个周期就报警",
                            alertRuleVo.getFunctionName(),
                            alertRuleVo.getOperator(),
                            alertRuleVo.getValue(),
                            alertRuleVo.getDuration());
            alertRuleVo.setRules(rules);
        });
        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 获取单个告警规则
     *
     * @param id
     * @return
     */
    @Override
    public AlertRuleVo showAlertRuleById(Integer id) {
        return alertRuleMapper.selectAlertRuleById(id);
    }

    /**
     * 更新告警规则
     *
     * @param alertRuleDto
     */
    @Override
    public void updateAlertRuleById(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateAlertRuleById(alertRule);
    }

    /**
     * 启用-禁用
     *
     * @param id
     * @param status
     */
    @Override
    public void updateAlertRuleStatusById(Long id, Integer status) {
        alertRuleMapper.updateAlertRuleStatusById(id, status);
    }

    /**
     * 删除告警规则
     *
     * @param id
     */
    @Override
    public void deleteAlertRuleById(Long id) {
        alertRuleMapper.deleteAlertRuleById(id);
    }

    /**
     * 定时任务查询所有报警规则
     *
     * @param iotId
     * @param productKey
     * @param functionId
     * @return
     */
    @Override
    public List<AlertRule> showAlertRule(String iotId, String productKey, String functionId) {
        return alertRuleMapper.selectAlertRule(iotId, productKey, functionId);
    }

    /**
     * 遍历每条数据进行报警规则比较
     *
     * @param deviceDataVo
     */
    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
        //判断该数据是否1分钟前的数据
        LocalDateTime alarmTime = deviceDataVo.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }

        //获取全部设备的报警规则
        List<AlertRule> alertRuleAllList = alertRuleMapper.selectAlertRule("-1", deviceDataVo.getProductKey(), deviceDataVo.getFunctionId());
        //获取该设备的报警规则
        List<AlertRule> alertRuleList = alertRuleMapper.selectAlertRule(deviceDataVo.getIotId(), deviceDataVo.getProductKey(), deviceDataVo.getFunctionId());
        Collection<AlertRule> alertRules = CollUtil.addAll(alertRuleAllList, alertRuleList);
        //判断报警规则是否为空，为空直接结束程序
        if (ObjectUtil.isEmpty(alertRules)) {
            return;
        }

        //报警规则不为空，便利进行规则校验
        alertRules.forEach(alertRule -> deviceDateAlarmHandler(alertRule, deviceDataVo));
    }

    //设备维护人员的角色名称
    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    //超级管理员的角色名称
    @Value("${zzyl.alert.managerRole}")
    private String managerRole;

    /**
     * 设备日期报警处理程序
     *
     * @param alertRule    报警规则
     * @param deviceDataVo 上报的数据
     */
    public void deviceDateAlarmHandler(AlertRule alertRule, DeviceDataVo deviceDataVo) {
        //第一层校验：判断是否在生效时段内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        LocalTime alarmTime = LocalDateTimeUtil.of(deviceDataVo.getAlarmTime()).toLocalTime();
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            return;
        }

        //获取设备id
        String iotId = deviceDataVo.getIotId();
        //生成报警计数器key
        String alertCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX +
                iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();

        //第二层校验：将设备上报值和阈值比较
        int compare = NumberUtil.compare(Double.parseDouble(deviceDataVo.getDataValue()), alertRule.getValue());
        if ((compare >= 0 && alertRule.getOperator().equals(">=")) || (compare < 0 && alertRule.getOperator().equals("<"))) {
            //此时设备上报数据达到阈值
            log.debug("此时设备上报数据达到阈值");
        } else {
            //没有达到阈值，删除redis报警数，结束程序
            redisTemplate.delete(alertCountKey);
            return;
        }

        //第三层校验：校验当前设备+功能的报警规则是否处于沉默周期
        String silentCacheKey = CacheConstants.ALERT_SILENT_PREFIX +
                iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId(); //生成沉默周期key
        String silentData = redisTemplate.opsForValue().get(silentCacheKey);
        if (ObjectUtil.isNotEmpty(silentData)) {
            //沉默周期不为空，说明还在沉默周期中，直接结束程序
            return;
        }

        //第四层校验：校验持续周期
        String alertCount = redisTemplate.opsForValue().get(alertCountKey);//获取redis中持续周期次数
        int triggerCount = ObjectUtil.isEmpty(alertCount) ? 1 : Integer.parseInt(alertCount) + 1; //判断是否为空，空设置1，不为空值+1

        if (triggerCount != alertRule.getDuration()) {
            //报警次数与持续周期不等，redis中设置新持续周期次数，结束程序
            redisTemplate.opsForValue().set(alertCountKey, String.valueOf(triggerCount));
            return;
        }

        //校验全部通过，当前数据触发报警
        redisTemplate.delete(alertCountKey); //删除redis报警数
        redisTemplate.opsForValue().set(silentCacheKey, deviceDataVo.getDataValue(), alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES); //添加redis沉默周期

        //判断是否为老人数据
        List<Long> consumerIds = null;
        if (ObjectUtil.equals(0, alertRule.getAlertDataType())) {
            //是老人数据，判断是否是固定设备
            if (deviceDataVo.getLocationType().equals(1) && deviceDataVo.getPhysicalLocationType().equals(2)) {
                //绑定的是固定设备，根据iotId通过床位查询老人护理人员ids
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }else if (deviceDataVo.getLocationType().equals(0)){
                //绑定的是随身设备，通过老人查询护理员ids
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }
        }else {
            //不是老人数据，通知维修人员,根据指定角色名称查询相关用户
            consumerIds = userRoleMapper.selectUserIdsByRoleName(deviceMaintainerRole);
        }

        //超级管理员可以收到所有消息
        List<Long> managerIds = userRoleMapper.selectUserIdsByRoleName(managerRole);
        List<Long> allConsumerIds = CollUtil.addAllIfNotContains(consumerIds, managerIds);//合并
        allConsumerIds = CollUtil.distinct(allConsumerIds); //去重

        //新增报警数据
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);

        List<AlertData> list = allConsumerIds.stream().map(id -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(id);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataMapper.insertAlertData(list);

        // websocket通知：弹窗消息
        AlertNotifyDto alertNotifyDto = BeanUtil.toBean(alertData, AlertNotifyDto.class);
        alertNotifyDto.setFunctionName(alertRule.getFunctionName());
        alertNotifyDto.setAlertDataType(alertData.getType());
        alertNotifyDto.setNotifyType(1);
        //给指定消费者发送消息
        webSocketServer.sendMessageToConsumer(alertNotifyDto, allConsumerIds);
    }
}
